package com.ecommerce.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Queue;

public class DatabaseConnection {
    private static final String URL = "jdbc:mysql://localhost:3306/ecommerce_system?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "Wdf323013916";

    // 简单的连接池
    private static final int POOL_SIZE = 5;
    private static final Queue<Connection> connectionPool = new LinkedList<>();

    static {
        initializeConnectionPool();
    }

    private static void initializeConnectionPool() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            for (int i = 0; i < POOL_SIZE; i++) {
                Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
                connectionPool.offer(conn);
            }
            System.out.println("数据库连接池初始化成功！");
        } catch (Exception e) {
            System.out.println("数据库连接池初始化失败: " + e.getMessage());
        }
    }

    public static Connection getConnection() throws SQLException {
        synchronized (connectionPool) {
            if (!connectionPool.isEmpty()) {
                return connectionPool.poll();
            }
        }
        // 如果连接池为空，创建新连接
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static void releaseConnection(Connection conn) {
        if (conn != null) {
            synchronized (connectionPool) {
                if (connectionPool.size() < POOL_SIZE) {
                    connectionPool.offer(conn);
                } else {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        System.out.println("关闭连接失败: " + e.getMessage());
                    }
                }
            }
        }
    }
}